import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.MouseEvent;

import CircleModel;
class CircleController
{
  private static inline var EASING:Float = 0.1;
  static private var SPEED_LIMIT:Float = 10;
  private var _model:CircleModel;
  private var _stage:Dynamic;

  public function new(model:CircleModel) 
  {
    _model = model;
  }
  public function processKeyDown(event:KeyboardEvent)
  {
    _model.friction = 1;
    if(event.keyCode == Keyboard.LEFT)
    {
      _model.acceleration_X = -1;
    }
    if(event.keyCode == Keyboard.RIGHT)
    {
      _model.acceleration_X = 1;
    }
    if(event.keyCode == Keyboard.UP)
    {
      _model.acceleration_Y = -1;
    }
    if(event.keyCode == Keyboard.DOWN)
    {
      _model.acceleration_Y = 1;
    }
    if(event.keyCode == Keyboard.ENTER)
    {
      _model.exit = true;
    }
  }
  
  public function processKeyUp(event:KeyboardEvent)
  {
  if(event.keyCode == Keyboard.LEFT
  ||(event.keyCode == Keyboard.RIGHT))
    {
      _model.acceleration_X = 0;
    }
    if(event.keyCode == Keyboard.UP
  ||(event.keyCode == Keyboard.DOWN))
    {
      _model.acceleration_Y = 0;
    }
  _model.friction = AVerletModel.frictionConstant;
  }
  
  public function processMouseDown
      (event:MouseEvent, stage:Dynamic)
  {
    _model.friction = 1;
  
  //Calculate the distance from the Dynamic to the mouse
    var vx:Float = stage.mouseX - _model.xPos;
    var vy:Float = stage.mouseY - _model.yPos;
    
    //Unoptimized easing:
    /*
    var m:Float = Math.sqrt(vx * vx + vy * vy);
    if (m >= 1)
    {...
    */
    
    //Optimized easing (does away with Math.sqrt):
    var m:Float = vx * vx + vy * vy;
    var range:Int = 1;
    
    //Move the Dynamic if it is more than 1 pixel away from the mouse
    if (m >= range * range)
    {
      _model.vx += (stage.mouseX - _model.xPos) * EASING / 2;
      _model.vy += (stage.mouseY - _model.yPos) * EASING / 2;
    }
  }
    public function processUpdate()
  {
    if(_model.acceleration_X == 0)
    { 
      _model.vx = _model.vx *.25;
    }
    if(_model.acceleration_Y == 0)
    { 
      _model.vy = _model.vy *.25;
    }
    if(_model.vx < -SPEED_LIMIT)
    {  
      _model.vx = -SPEED_LIMIT;
    }
    if(_model.vx > SPEED_LIMIT)
    {  
      _model.vx = SPEED_LIMIT;
    }
  }
  public function processMouseUp(event:MouseEvent)
  {
    _model.friction = AVerletModel.frictionConstant;
  }
}